package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.eventbus.BigImageEvent;
import com.asktgapp.model.EngineerVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/24
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:工程师列表
 */

public class EngineerListFragment extends BaseFragment {
    private RefreshRecyclerView mRefreshRecyclerView;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private EditText etSearch;
    private TextView tvDelete;
    private int mPage = 1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_engineer_list, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mRefreshRecyclerView = rootView.findViewById(R.id.recycle);
        etSearch = rootView.findViewById(R.id.etSearch);
        tvDelete = rootView.findViewById(R.id.tvDelete);
        etSearch.setFilters(new InputFilter[]{new EmojiFilter()});
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mPage=1;
                if (s.length() > 0) {
                    tvDelete.setVisibility(View.VISIBLE);
                    if (!Utils.noContainsEmoji(s.toString())) {
                        showTost("不支持输入emoji表情", 1);
                        return;
                    }
                    getData(mPage,s.toString());
                } else {
                    getData(mPage,null);
                    tvDelete.setVisibility(View.INVISIBLE);
                }
            }
        });

        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
                tvDelete.setVisibility(View.INVISIBLE);
                mPage=1;
                getData(mPage,null);
            }
        });

        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData(mPage,null);
            }
        });
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData(mPage,null);
            }
        });
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_engineer, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                if (data instanceof EngineerVO) {
                                    final EngineerVO bean = (EngineerVO) data;
                                    ImageView headImg = holder.getView(R.id.iv_head_engineer);
                                    ImageView userRanke = holder.getView(R.id.userRanke);

                                    if(bean.getUserRanke().equals("1"))
                                        userRanke.setImageResource(R.mipmap.reank_1);
                                    else if(bean.getUserRanke().equals("2"))
                                        userRanke.setImageResource(R.mipmap.reank_2);
                                    else if(bean.getUserRanke().equals("3"))
                                        userRanke.setImageResource(R.mipmap.reank_3);
                                    else if(bean.getUserRanke().equals("4"))
                                        userRanke.setImageResource(R.mipmap.reank_4);
                                    else if(bean.getUserRanke().equals("5"))
                                        userRanke.setImageResource(R.mipmap.reank_5);

                                    headImg.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            seeBigPic(0,  bean.getUserPic());
//                                            BigImageEvent.postEvent("http://cdn.duitang.com/uploads/item/201507/10/20150710045602_wHEBf.jpeg");
                                        }
                                    });
                                    TextView mTag1 = holder.getView(R.id.tv_tag1);
                                    TextView mTag2 = holder.getView(R.id.tv_tag2);
                                    ImageDisplayUtil.loadCircleHeadImage(getActivity(), headImg, bean.getUserPic());
//                                    holder.setText(R.id.tv_reason, bean.getRecommendReason());
                                    if (!TextUtils.isEmpty(bean.getRecommendReason())) {
                                        String[] arr = bean.getRecommendReason().trim().split("##");
                                        String recommend = "";
                                        for (int i = 0; i <arr.length ; i++) {
                                            recommend += "★  "+arr[i]+"\n";
                                        }
                                        holder.setText(R.id.tv_reason, recommend);
                                    }
                                    holder.setText(R.id.tv_price, "¥ " + Utils.D2S(bean.getAdvisoryPrice()) + "元");

                                    holder.setText(R.id.tv_name, bean.getRealname());

                                    String pro = bean.getProviceName().replaceAll("省", "");
                                    String city = bean.getCityName().replaceAll("市", "");

                                    if (TextUtils.isEmpty((pro + " " + city).trim()))
                                        holder.setText(R.id.tvAddress, "未知地区");
                                    else
                                        holder.setText(R.id.tvAddress, pro + " " + city);
                                    holder.setText(R.id.answerNum,"解答 "+bean.getAnswerTimes()+"条");
                                    holder.setText(R.id.grade, "评分 "+bean.getUserGrade());
                                   if(!TextUtils.isEmpty(bean.getLabel())){
                                       String[] str = bean.getLabel().split(",");
                                       if (str.length == 0) {
                                           mTag1.setVisibility(View.GONE);
                                           mTag2.setVisibility(View.GONE);
                                       } else if (str.length == 1) {
                                           if (Util.isEmpty(str[0])) {
                                               mTag1.setVisibility(View.GONE);
                                           } else {
                                               mTag1.setVisibility(View.VISIBLE);
                                           }
                                           mTag2.setVisibility(View.GONE);
                                           mTag1.setText(str[0]);
                                       } else if (str.length >= 2) {
                                           mTag1.setVisibility(View.VISIBLE);
                                           mTag2.setVisibility(View.VISIBLE);
                                           mTag1.setText(str[0]);
                                           mTag2.setText(str[1]);
                                       }
                                   }else {
                                       mTag1.setVisibility(View.GONE);
                                       mTag2.setVisibility(View.GONE);
                                   }
                                    if(bean.getIsShow()==1){
                                        holder.getView(R.id.ivRenZ).setVisibility(View.VISIBLE);
                                    }else {
                                        holder.getView(R.id.ivRenZ).setVisibility(View.INVISIBLE);
                                    }
                                }
                            }

                            @Override
                            public void onItemClick(View view, int position) {
                                EngineerVO bean = (EngineerVO) mBaseAdapter.getData().get(position);
                                Intent intent = new Intent(getActivity(), EngineerDetailActivity.class);
                                intent.putExtra("id", bean.getId());
                                startActivity(intent);


                            }
                        });
                return holder;
            }
        };
        mRecyclerView.setAdapter(mBaseAdapter);

    }

    @Override
    public void loadData() {
        visibleLoading();
        getData(mPage,null);
    }


    public void getData(final int mPage, final String content) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("page", mPage);
        if(!TextUtils.isEmpty(content))
            params.put("content", content);
        Call<ApiResponseBody<List<EngineerVO>>> call = apiservice.selProjecterList(params);
        call.enqueue(new Callback<ApiResponseBody<List<EngineerVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<EngineerVO>>> call, Response<ApiResponseBody<List<EngineerVO>>> response) {
                inVisibleLoading();
                mRefreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    List<EngineerVO> list = response.body().getResult();
                    if (mPage == 1) {
                        if (list.size() == 0) {
                            visibleNoData();
                        } else {
                            mBaseAdapter.setData(list);
                            if(TextUtils.isEmpty(content)){
                                mRefreshRecyclerView.showNextMore(mPage);
                            }
                        }
                    } else {
                        if (list.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<EngineerVO>>> call, Throwable t) {
                inVisibleLoading();
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bigIamge(BigImageEvent event) {
//        if(!TextUtils.isEmpty(event.getImageUrl())){
        seeBigPic(0, event.getImageUrl());
//        }
    }
}
